
# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView, ListAPIView

# Create your views here.

from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.permissions import IsAdminUser,IsAuthenticated



from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAdminUser,IsAuthenticated

from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler

from ElroyDn.serializer import QuestionSerializer, LabelSerializer, AwaitSerializer, HotSerializer, NewSerializer
    # QuestionsSerializer,Usersializer,SpitSerializer
from rest_framework.response import Response

from GoldenSnow.serializers import SpitModelSerializer
from GoldenSnow.utils import PageNumber
from xyz.models import Question, Label,Reply,User,Spit


# 所有标签
class LabelsAPIView(APIView):
    def get(self, request):
        labels = Label.objects.all()
        serializer = LabelSerializer(labels, many=True)
        return Response(serializer.data)


# 等待回答
class WaitAPIView(APIView):

    def get(self, request, pk):
        if pk == "-1":
            question = Question.objects.filter(reply=0).order_by('-visits')
            serializer = AwaitSerializer(question, many=True)
        else:
            question = Question.objects.filter(labels=pk,reply=0).order_by('-visits')
            serializer = AwaitSerializer(question,many=True)
        return Response(serializer.data)


# 热门回答
class HotAPIView(APIView):

    def get(self, request, pk):
        if pk == "-1":
            question = Question.objects.all().order_by('-visits')
            serializer = HotSerializer(question, many=True)
        else:
            question = Question.objects.filter(labels=pk).order_by('-visits')
            serializer = HotSerializer(question,many=True)
        return Response(serializer.data)


# 最新回答
class NewAPIView(APIView):
    def get(self, request, pk):

        if pk == "-1":
            question = Question.objects.all().order_by('-createtime')
            serializer = NewSerializer(question, many=True)
        else:
            question = Question.objects.filter(labels=pk).order_by('-createtime')
            serializer = NewSerializer(question, many=True)
        return Response(serializer.data)


# 发布问题
class QuestionCreateAPIView(CreateAPIView):

    permission_classes = [IsAuthenticated ]

    queryset = Question
    serializer_class = QuestionSerializer

    def create(self, request, *args, **kwargs):
        create_data = request.data
        user = request.user.id
        create_data['user'] = user
        title = create_data.get('title')
        content = create_data.get('content')
        labels1 = create_data.get('labels')
        question = Question.objects.create(content=content, title=title, user_id=user)
        for i in labels1:
            labels2 = i
            question.labels.add(labels2)
        # question.save()
        return Response({"message": "问题发布成功", "success": True})








class SpitAPIView(CreateAPIView,ListAPIView):
    # permission_classes = [IsAuthenticated]
    queryset = Spit.objects.all().order_by('-publishtime')

    serializer_class = SpitModelSerializer

    def get(self, request, *args, **kwargs):

        try:

            token = self.request.auth

            token_user = jwt_decode_handler(token)

            user_id = token_user['user_id']

        except Exception as e:

            return Response(status=404)

        redis_conn = get_redis_connection('spit')
        list = []
        spits = Spit.objects.filter(parent_id=None)
        for spit in spits:
            if redis_conn.sismember('collect_%s' % spit.id, user_id):
                collected = True
            else:
                collected = False
            if redis_conn.sismember('thumbup_%s' % spit.id, user_id):
                hasthumbup = True
            else:
                hasthumbup = False
            serializer = SpitModelSerializer(spit)
            serializer.data['collected'] = collected
            serializer.data['hasthumbup'] = hasthumbup
            list.append(dict(serializer.data,**{'collected':collected,'hasthumbup':hasthumbup}))
        return Response(list)

        # redis_conn.sismember('collect_%s' % id, user_id)
        # redis_conn.sismember('thumbup_%s' % id, user_id)
    # #     collected
    #     hasthumbup

    # pagination_class = PageNumber


    # def post(self,request):
    #     data=request.data
    #     print(request.data.get('content'))
    #     parent=request.data.get('parent')
    #     if parent:
    #         try:
    #             token = self.request.auth
    #             toke_user = jwt_decode_handler(token)
    #             user_id = toke_user["user_id"]
    #         except Exception as e:
    #             return Response('收藏失败，请先登录',status=404)
    #
    #         return self.create(request,user_id=user_id)
    #     else:
    #         return self.create(request)



















    def create(self, request, *args, **kwargs):

        create_data = request.data
        # serializer = SpitSerializer(data=create_data)
        # serializer.is_valid()
        # serializer.save()
        # # title = create_data.get('title')
        parent = create_data.get('parent')
        content = create_data.get('content')
        if parent is None:


            # # labels1 = create_data.get('labels')
            # # for i in labels1:
            # #     labels2 = i
            question = Spit.objects.create(content=content)
            # # question.labels.add(labels2)
        else:
            question = Spit.objects.create(content=content, parent_id=parent)
        serializer=SpitModelSerializer(question)

        return Response(serializer.data)







from ElroyDn.serializer import CommentSerializer
from django import http

# 问题详情
class QuestionsAPIView(APIView):
    def get(self,request,pk):
        question=Question.objects.get(id=pk)
        serializer=CommentSerializer(question)
        question.reply += 1
        question.visits += 1
        question.save()
        return Response(dict(serializer.data,**{'comment_question':[]}))
        # return Response(serializer1.data)
        # reply=Reply.objects.all()
        # serializer=CommentSerializer(reply,many=True)
        # content={
        #     'id':serializer.data.get('id'),
        #     'createtime':serializer.data.get('createtime'),
        #     'labels':serializer.data.get('labels'),
        #     'reply':serializer.data.get('reply'),
        #     'replyname':serializer.data.get('replyname'),
        #     'title':serializer.data.get('title'),
        #     'unuseful_count':serializer.data.get('unuseful_count'),
        #     'useful_count':serializer.data.get('useful_count'),
        #     'user':serializer.data.get('user'),
        #     'visits':serializer.data.get('visits'),
        #     'content':serializer.data.get('content'),
        #     'comment_question':serializer1.data,
        #     'answer_question':serializer1.data,
        #
        # }
        # return Response(content)



# 用户关注标签
class LabelUsersAPIView(APIView):
    def get(self,request):
         labels=Label.objects.all()
         serializer=LabelSerializer(labels,many=True)

         return Response(serializer.data)


